﻿using System;
using CustomerContactSystem.Core.AppServices.Email;
using CustomerContactSystem.Core.Model;

namespace CustomerContactSystem.WebForms
{
    public partial class ChangePassword : BasePage {
        protected void Page_Load(object sender, EventArgs e) {
        }

        protected void SaveNewPasswordClick(object sender, EventArgs e) {
            if ((LoggedUser == null)) {
                return;
            }

            if (!IsPageValid(LoggedUser)) {
                return;
            }

            LoggedUser.Password = Password.Text;

            UserRepository.Update(LoggedUser);

            var loginInfoEmail = new LoginDetailsEmail(ConfigSettings.AdminEmailAddress,
                                                       LoggedUser.Email, LoggedUser.Username,
                                                       LoggedUser.Password);
            //var smtpService = new SmtpEmailService(ConfigSettings.GetStringSetting("SmptServerAddress"));
            EmailService.SendEmail(loginInfoEmail);
            ChangePasswordContent.Visible = false;
            PasswordChangedContent.Visible = true;
        }

        private bool IsPageValid(User u)
        {
            if (OldPassword.Text.Trim().Length == 0)
            {
                ErrorMsg.Text = "Please enter your current password!";
                return false;
            }

            if (Password.Text.Trim().Length == 0 | Password.Text.Trim().Length < 8)
            {
                ErrorMsg.Text = "Password must be at least 8 characters long!";
                return false;
            }

            if (Password.Text.Trim() != Password2.Text.Trim())
            {
                ErrorMsg.Text = "Please enter your current password!";
                return false;
            }

            if (OldPassword.Text.Trim() != u.Password)
            {
                ErrorMsg.Text = "Incorrect current password entered!";
                return false;
            }

            return true;
        }
    }
}